<template>
  <!-- 重置密码弹窗 -->
  <el-dialog
    :title="$t('login.mima1')"
    :visible.sync="dialogShow"
    width="800px"
    height="573px"
    :close-on-click-modal="false"
  >
    <div class="reset_password_inner">
      <el-form
        ref="form"
        :rules="rules"
        label-position="left"
        :label-width="labelWidth"
        :model="form"
      >
        <el-form-item :label="$t('zhuce.zhuce35')" prop="phoneOrEmail">
          <!-- <el-input v-model="form.phoneOrEmail" :placeholder="$t('login.mima3')" /> -->
          <div class="phone_box" :class="['phone_box', getBorder]">
            <div class="ease_animation" :style="{ width: isShowAreaCode ? '90px' : '0px' }">
              <el-select v-model="phoneCode" slot="prepend" style="width: 90px">
                <el-option
                  :label="item.paramValue"
                  :value="item.id"
                  v-for="(item, index) in phoneCodeList"
                  :key="index"
                ></el-option>
              </el-select>
            </div>
            <el-input
              v-model="form.phoneOrEmail"
              :placeholder="$t('patient.huanzhe28')"
              @blur="emailBlur"
              @focus="emailFocus"
              @input="emailChange"
              maxlength="100"
            >
            </el-input>
          </div>
        </el-form-item>
        <el-form-item :label="$t('login.mima4') + '：'" prop="password">
          <el-input v-model="form.password" type="password" :placeholder="$t('login.mima5')"  maxlength="100" />
        </el-form-item>
        <el-form-item :label="$t('login.mima6') + '：'" prop="password2">
          <el-input v-model="form.password2" type="password" :placeholder="$t('login.mima7')"  maxlength="100" />
        </el-form-item>
        <el-form-item :label="$t('login.mima8') + '：'" prop="code" class="formItem_code">
          <el-input
            type="textarea"
            :rows="2"
            :autosize="false"
            v-model="form.code"
            :placeholder="$t('login.mima9')"
             maxlength="100"
          />
          <span class="code_btn" @click="getyzm">{{ buttonName }}</span>
        </el-form-item>
      </el-form>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="resetHandleClose">{{ $t('login.mima10') }}</el-button>
      <el-button type="primary" @click="submitForm()">{{ $t('login.mima18') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { isMobile, isEmail } from '@/utils/validate';

export default {
  props: {},
  data() {
    const validateEmail = (rule, value, callback) => {
      if (value === '') {
        this.phoneLegal = false;
        callback(new Error(this.$t('login.mima3')));
      } else {
        if (value.includes('@')) {
          // 是邮箱
          if (!isEmail(this.form.phoneOrEmail)) {
            this.phoneLegal = false;
            callback(new Error(this.$t('login.mima13')));
          } else {
            this.phoneLegal = true;
            callback();
          }
        } else {
          if (!isMobile(this.form.phoneOrEmail)) {
            this.phoneLegal = false;
            callback(new Error(this.$t('zhuce.zhuce18')));
          } else {
            this.phoneLegal = true;
            callback();
          }
        }
      }
    };
    let validatePwd = (rule, value, callback) => {
      let pwdRule = new RegExp(
        /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[a-zA-Z])[0-9a-zA-Z!#$%&'()*+,-./:;<=>?@~!%^¥,\.]{8,32}$/,
      );
      if (pwdRule.test(value)) {
        callback();
      } else {
        callback(this.$t('zhuce.zhuce31'));
      }
    };
    let validateCode = (rule, value, callback) => {
      if (value) {
        callback();
      } else {
        callback(this.$t('zhuce.zhuce24'));
      }
    };
    return {
      // 手机号输入框是否点击过
      isClick: false,
      // 定义变量确定是否聚焦
      isFocus: false,
      // 手机号或者邮箱是否合法
      phoneLegal: true,
      // 定义区号是否出现
      isShowAreaCode: false,
      phoneCodeList: [],
      // 定义验证码按钮的点击次数
      clickCount: 0,
      phoneCode: '85',

      form: {
        code: '',
        password: '',
        password2: '',
        phoneOrEmail: '',
      },
      labelWidth: '125px',
      rules: {
        code: [
          {
            validator: validateCode,
            trigger: 'blur',
          },
        ],
        password: [
          {
            validator: validatePwd,
            trigger: 'blur',
          },
        ],
        password2: [
          {
            validator: validatePwd,
            trigger: 'blur',
          },
        ],
        phoneOrEmail: [
          {
            validator: validateEmail,
            trigger: 'blur',
          },
        ],
      },
      dialogShow: false,
      // buttonName: this.getButtonName(),
      count: 60,
      isShow: false,
      // 定义定时器是否开始
      isCountdown: false,
      // rules: rules.rules //公共校验规则
      timer: null,
    };
  },
  watch: {
    '$i18n.locale': 'i18nHandle',
  },
  created() {
    this.i18nHandle(this.$i18n.locale);
    // 获取手机号区号数据
    this.getPhoneArea();
  },
  computed: {
    buttonName: function () {
      if (this.isCountdown) {
        // 开了定时器
        if (this.isShow) {
          return this.count + this.$t('login.mima15');
        } else {
          return this.$t('login.mima16');
        }
      } else {
        // 没开过定时器
        return this.$t('login.mima12');
      }
    },
    getBorder: function () {
      let className = '';
      if (this.isClick) {
        if (this.isFocus) {
          if (this.phoneLegal) {
            className = 'curr_phone_box';
          } else {
            className = 'red_phone_box';
          }
        } else {
          if (this.phoneLegal) {
            className = 'curr_phone_box';
          } else {
            className = 'red_phone_box';
          }
        }
      }

      return className;
    },
  },
  methods: {
    getPhoneArea() {
      this.$http
        .get('/sys/params/page?page=1&limit=9999&paramCode=phoneNumber&paramType=1')
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.phoneCodeList = res.data.list;
          }
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    emailBlur(val) {
      this.isFocus = false;
    },
    emailFocus() {
      this.isClick = true;
      this.isFocus = true;
    },
    emailChange() {
      if (this.form.phoneOrEmail.length >= 4) {
        if (!this.form.phoneOrEmail.includes('@')) {
          this.isShowAreaCode = true;
        } else {
          this.isShowAreaCode = false;
        }
      } else {
        this.isShowAreaCode = false;
      }
    },
    i18nHandle(val, oldVal) {
      if (val === 'cn') {
        this.labelWidth = '105px';
      } else if (val === 'en') {
        this.labelWidth = '170px';
      } else if (val === 'pt') {
        this.labelWidth = '210px';
      }
    },
    colseSendCode() {
      this.isShow = false;
      this.count = 60;
      clearInterval(this.timer);
      this.timer = null;
    },
    resetHandleClose() {
      this.dialogShow = false;
      this.$refs.form.resetFields(); // 关闭弹窗输入框清空
      this.colseSendCode();
    },
    // 获取验证码
    getyzm() {
      
      if (this.isShow) {
        return false;
      }
      if (this.form.phoneOrEmail.includes('@')) {
        if (!this.phoneLegal) {
          return this.$message.error(this.$t('login.mima13'));
        }
      } else {
        if (!this.phoneLegal) {
          return this.$message.error(this.$t('zhuce.zhuce18'));
        }
      }

      const lang = localStorage.getItem('lang');
      this.clickCount++;
      if(this.clickCount !== 1){
        return false;
      }
      if (this.form.phoneOrEmail.includes('@')) {
        this.$http
          .get(
            `/open/sms/sendSms?uniqueKey=${this.form.phoneOrEmail}&type=RESET_PASSWORD&lang=${lang}`,
          )
          .then(({ data: res }) => {
            if (res.code !== 0) {
              this.clickCount = 0;
              return this.$message.error(res.msg);
            } else {
            
              this.$message.success(this.$t('zhuce.zhuce30'));
              this.count = 60;
              this.isShow = true;

              this.timer = setInterval(() => {
                this.isCountdown = true;

                if (this.count > 0 && this.count <= 60) {
                  this.count--;

                } else {
                  this.isShow = false;
                  this.clickCount = 0;

                  clearInterval(this.timer);
                }
              }, 1000);
            }
          })
          .catch((err) => {
            this.clickCount = 0;
            console.log('err', err);
          });
      } else {
        let formData = new FormData();
        formData.append('phone', this.form.phoneOrEmail);
        this.$http
          .post('/smsMessage/send', formData)
          .then((res) => {
            if (res.data.code !== 0) {
              this.clickCount = 0;
              return this.$message.error(res.data.msg);
            } else {
              this.$message.success(this.$t('zhuce.zhuce36'));
              this.count = 60;
              this.isShow = true;

              this.timer = setInterval(() => {
                this.isCountdown = true;

                if (this.count > 0 && this.count <= 60) {
                  this.count--;
                } else {
                  this.isShow = false;
                  this.clickCount = 0;
                  clearInterval(this.timer);
                }
              }, 1000);
            }
          })
          .catch((e) => {
            this.clickCount = 0;
            console.error(e);
          });
      }
    },
    // 提交
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let url = '';
          if (this.form.phoneOrEmail.includes('@')) {
            // 邮箱
            url = '/open/resetPassword';
          } else {
            // 手机号
            url = '/open/resetPasswordPhone';
          }

          this.$http
            .post(url, {
              ...this.form,
              lang: localStorage.getItem('lang'),
            })
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              } else {
                this.dialogShow = false;
                this.form = {
                  code: '',
                  password: '',
                  password2: '',
                  phoneOrEmail: '',
                };
                this.$message.success(this.$t('login.login2'));
                this.colseSendCode();
              }
            })
            .catch((err) => {
              console.log('err', err);
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 取消重置
  },
};
</script>

<style lang="scss" scoped>
.reset_password_inner {
  ::v-deep .el-form-item {
    margin-bottom: 45px;
  }
}

.reset_password_inner {
  padding: 24px 140px;
}

.formItem_code {
  position: relative;

  .code_btn {
    position: absolute;
    right: 23px;
    top: 25px;
    color: #003e67;
    cursor: pointer;
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    line-height: 25px;
    color: #003e67;
  }
}

textarea {
  resize: none;
  /* 禁止拉伸 */
}
</style>
